package com.mini.rpc.protocol.serialization;

import com.caucho.hessian.io.HessianSerializerInput;
import com.caucho.hessian.io.HessianSerializerOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author lbx
 * @version 1.0.0
 * @description TODO
 * @date 2021/10/5 14:01
 **/
public class HessianSerialization implements RpcSerialization {
    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        if (obj == null) {
            throw new NullPointerException();
        }
        byte[] result;

        HessianSerializerOutput hessianSerializerOutput;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            hessianSerializerOutput = new HessianSerializerOutput(os);
            hessianSerializerOutput.writeObject(obj);
            hessianSerializerOutput.flush();
            result = os.toByteArray();
        } catch (Exception e) {
            throw new SerializationException(e);
        }
        return result;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) throws IOException {
        if (data == null) {
            throw new NullPointerException();
        }
        T result;

        try (ByteArrayInputStream is = new ByteArrayInputStream(data)) {
            HessianSerializerInput hessianSerializerInput = new HessianSerializerInput((is));
            result = (T) hessianSerializerInput.readObject(clz);

        } catch (Exception e) {
            throw new SerializationException(e);
        }
        return result;
    }
}
